class Router {
  constructor() {
    this.middlewares = [];
  }
  get(pathname, middleware) {
    this.middlewares.push({
      path: pathname,
      middleware: middleware,
      method: "get",
    });
  }
  routes() {
    return async (ctx, next) => {
      //  获取请求方法
      let method = ctx.method.toLowerCase();
      let path = ctx.path;
      // 过滤出匹配的路径对象
      let arr = this.middlewares.filter((middleware) => {
        return middleware.method === method && middleware.path === path;
      });
      //   console.log(arr);
      this.compose(arr, next);
    };
  }
  compose(arr, next, ctx) {
    function dispatch(index) {
      // 如果超出了router设置的中间件，则使用默认中间件use
      if (arr.length === index) return next();
      //  取出第一个路由执行
      let middle = arr[index];
      return Promise.resolve(middle.middleware(ctx, () => dispatch(index + 1)));
    }
    return dispatch(0);
  }
//   allowedMethods() {
//     return async (ctx, next) => {};
//   }
}
module.exports = Router;
